package com.bigfreakindeals.Activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes.Name;

import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Adapters.ShareAdapter;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.AsynchListener;
import com.bigfreakindeals.Controller.ClosestSchoolListener;
import com.bigfreakindeals.Controller.GPSController;
import com.bigfreakindeals.Controller.GPSLocationListener;
import com.bigfreakindeals.Controller.ImageEngine;
import com.bigfreakindeals.Controller.ImageListener;
import com.bigfreakindeals.Controller.ZipDownloader;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.ShareItem;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Models.DrawableImageSlug;
import com.bigfreakindeals.Models.Highlights;
import com.bigfreakindeals.Models.ObjectImage;
import com.bigfreakindeals.Models.UniversityDeals;
import com.bigfreakindeals.Protocols.SoapHandlers.ClosestSchoolHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.GetTodaysDealHandler;
import com.bigfreakindeals.Widgets.AlertManager;

public class ActiveDealsActivity extends BaseActivity implements OnClickListener,AsynchListener, ImageListener, AnimationListener , GPSLocationListener ,ClosestSchoolListener{
	   // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

	
	RelativeLayout mainpage;

	RelativeLayout maindeals; // grayed area deals page
	RelativeLayout maindealsNoDeals; // grayed area no deals

	RelativeLayout thumbnailLayout;

	String[] shareitems = { "E-mail", "Post it on Facebook", "Tweet it on Twitter" };
	int[] shareitemsdrawable = { R.drawable.share_email_icon, R.drawable.facebook_icon, R.drawable.twitter_icon };

	WebView tabtextWebViewHL;
	WebView tabtextWebViewFP;
	WebView tabtextWebViewCOM;

	WebView tabDescWebView;
	RelativeLayout terms;
	View header;
	ListAdapter adapter;
	LinearLayout dealListView;
	Button headerButtonLeft;
	Button headerButtonRight;
	TextView beanSays;
	Button share;
	Button discuss;

	Animation contextMenuIn;
	Animation contextMenuOut;

	TextView timer;
	Button beanSaysNoDeals;
	Long remainingTimer = (long) 0;
Intent uiIntent;
	TextView headerTitle;
	Button tf_highLights;
	Button tf_finePrint;
	Button tf_company;
	LinearLayout headertopBG;

	LinearLayout headerbottomBG;
	RelativeLayout tabtext_bg;
	TextView tabtext;
	TextView noDealsErrorMessage;
	ActiveDeal active = new ActiveDeal();
	UniversityDeals universitydeals;
	boolean hasdeals = true;
	boolean rceieved = false;
	List<ActiveDeal> dealList;
	ArrayAdapter<String> adapter1;

	Calendar calendar = Calendar.getInstance();
	private Handler handler = new Handler();
	TextView linksTextView, linksView, textview3;

	LayoutInflater inflater;// r = (LayoutInflater)
							// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	String errormessage;
	View customView;
   
	
	ScrollView scrollview;
	private Runnable runnable = new Runnable() {
		@Override
		public synchronized void run() {
			/* do what you need to do */
			synchronized (remainingTimer) {
				reduceTimer();
				updateRemainingTime();
				/* and here comes the "trick" */
				handler.removeCallbacks(this);
				handler.postDelayed(this, 1000);
			}
			
		}
	};
	@Override
	public void handlerResponse(boolean isSuccess, Double longitude, Double latitude) {
		// TODO Auto-generated method stub
		Log.i("SPLASH SCREEN", " is success"+isSuccess+"long: "+longitude+"lat: "+latitude);
		
	}
	   
	


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		System.out.println("oncreate");
		contextMenuIn = AnimationUtils.loadAnimation(this, R.anim.footer_right_to_left);

		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool() != null){
			universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
		}
	
		
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter("SCHOOLLISTSELECTED"));
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter(Constant.EVENTS_GETACTIVEDEALS_ERROR));
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter(Constant.EVENTS_GETACTIVEDEALS_SUCCESS));
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter(Constant.EVENTS_GETBITMAPIMAGE));
		this.registerReceiver(activeDealsBRoadcastReceiver, new IntentFilter(Constant.EVENTS_GETCLOSESTSCHOOL));
		
		
		
		// init activedeals screen
		setContentView(R.layout.activedeals);
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		tabtextWebViewHL = (WebView) findViewById(R.id.text_bgHL);
		WebViewClient webViewClientExt = new WebViewClientExt();
		tabtextWebViewHL.setWebViewClient(webViewClientExt);
		tabtextWebViewHL.setVerticalScrollbarOverlay(true);
		//tabtextWebViewHL.setFocusableInTouchMode(true);
		//tabtextWebViewHL.requestFocus(View.FOCUS_UP);
		
		WebSettings webSettings = tabtextWebViewHL.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettings.setDomStorageEnabled(true);
		webSettings.setSaveFormData(false);
		webSettings.setSavePassword(false);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setBlockNetworkImage(false);

		tabtextWebViewFP = (WebView) findViewById(R.id.text_bgFP);
		WebViewClient webViewClientExtFP = new WebViewClientExt();
		tabtextWebViewFP.setWebViewClient(webViewClientExtFP);
		tabtextWebViewFP.setVerticalScrollbarOverlay(true);
		
		
		WebSettings webSettingsFP = tabtextWebViewFP.getSettings();
		webSettingsFP.setJavaScriptEnabled(true);
		webSettingsFP.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettingsFP.setDomStorageEnabled(true);
		webSettingsFP.setSaveFormData(false);
		webSettingsFP.setSavePassword(false);
		webSettingsFP.setLoadsImagesAutomatically(true);
		webSettingsFP.setBlockNetworkImage(false);

		tabtextWebViewCOM = (WebView) findViewById(R.id.text_bgDEAL);
		
		WebViewClient webViewClientExtCOM = new WebViewClientExt();
		tabtextWebViewCOM.setWebViewClient(webViewClientExtCOM);
		tabtextWebViewCOM.setVerticalScrollbarOverlay(true);
		//tabtextWebViewCOM.requestFocus(View.FOCUS_UP);
		
		WebSettings webSettingsCOM = tabtextWebViewCOM.getSettings();
		webSettingsCOM.setJavaScriptEnabled(true);
		webSettingsCOM.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettingsCOM.setDomStorageEnabled(true);
		webSettingsCOM.setSaveFormData(false);
		webSettingsCOM.setSavePassword(false);
		webSettingsCOM.setLoadsImagesAutomatically(true);
		webSettingsCOM.setBlockNetworkImage(false);

		tabDescWebView = (WebView) findViewById(R.id.tab_description);
		WebViewClient webViewClientDesc = new WebViewClientExt();
		tabDescWebView.setWebViewClient(webViewClientDesc);
		tabDescWebView.setVerticalScrollbarOverlay(true);
		//tabDescWebView.requestFocus(View.FOCUS_UP);
		WebSettings webSettingsDesc = tabDescWebView.getSettings();
		webSettingsDesc.setJavaScriptEnabled(true);
		webSettingsDesc.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettingsDesc.setDomStorageEnabled(true);
		webSettingsDesc.setSaveFormData(false);

		webSettingsDesc.setSavePassword(false);
		webSettingsDesc.setLoadsImagesAutomatically(true);
		webSettingsDesc.setBlockNetworkImage(false);
		
		if (universitydeals!=null){
			updateDrawable();
		}
		initActiveDealsScreen();

	}

	public class WebViewClientExt extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			
		}
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.e("BrowserActivity", "url" + url);

			if (url.contains("FAQ")) {
				// get the number
				Intent intent = new Intent(view.getContext(), BrowserActivity.class);
				intent.putExtra(Constant.TAG_BROWSERTYPE, (byte) Constant.type_FAQ);

				startActivity(intent);

			} else if (url.contains("PHONE")) {
				// get the number
				String number = "0";
				url = url.replaceAll(" ", "");
				if (url.indexOf(":") > 0) {
					number = url.substring(url.indexOf(":") + 1);
				}

				try {
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse("tel:" + number));
					startActivity(intent);
				} catch (Exception e) {
					showAlert("Failed to invoke call.", "OK");

				}

			} else if (url.contains("MAP")) {
				// get the number
				String lat,longi;
				
				url = url.replaceAll(" ", "");
				
				if (url.indexOf(":") > 0) {
					String param = url.substring(url.indexOf(":") + 1);
					if (param.indexOf("|") > 0) {
					lat = param.substring(0,param.indexOf("|"));

					longi = param.substring(param.indexOf("|")+1);
					Company company = universitydeals.getMainDeal().getCompany();
					
					//call map intent
					Intent intent = new Intent(view.getContext(), BigfreakinDealsMapsActivity.class);
					intent.putExtra(Constant.TAG_COMPANY_LATITUDE, lat);
					intent.putExtra(Constant.TAG_COMPANY_LONGITUDE, longi);
					intent.putExtra(Constant.TAG_COMPANY_NAME, company.getPlainString());
					intent.putExtra(Constant.TAG_COMPANY_DEALTITLE, universitydeals.getMainDeal().getDealName());
					ApplicationEx.getInstance().mapDrawable = ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getMainDeal().promoMapImage;
					
					startActivity(intent);

					}
						
				}
				
				
				
				
				
			} else if (url.contains("URL")) {
				// get the url
				try {
					if (url.indexOf("URL") == 0) {
						String newurl = url.substring(url.indexOf("URL") + 4);
						Uri uriUrl = Uri.parse(newurl);
						
						Intent i = new Intent(Intent.ACTION_VIEW, uriUrl);
						startActivity(i);
						
						
					}
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
					showAlert("The url your trying to access does not seem to be valid."+e.getLocalizedMessage(), "OK");
				}

			} else {
				String companyurl = url;
				Intent intent = new Intent(view.getContext(), BrowserActivity.class);
				intent.setData((Uri.parse(companyurl)));
				intent.putExtra(Constant.TAG_BROWSERTYPE, (byte) Constant.type_MAP);
				startActivity(intent);

			}

			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			 super.onPageFinished(view, url);
			 view.scrollTo(0, 0);
		}
		
		

	}

	public void showAlert(String message, String button) {
		AlertManager.alertOK(this.getParent(), message, button);

	}

	@Override
	public void handlerResponse(boolean isSuccess,boolean isRefresh) {
		// TODO Auto-generated method stub
		System.out.println("handler response");
		
		ApplicationEx.getInstance().controller.getTodaysDeal(isRefresh);
		
	}
	@Override
	public void onResume() {
		super.onResume();
		System.out.print("onresume@activedeals");
		
		ApplicationEx.getInstance().currentTab = 0;
		
		try {
			if (ApplicationEx.getInstance().progressDialog != null)
				ApplicationEx.getInstance().progressDialog.dismiss();

		} catch (Exception e) {
			// TODO: handle exception
		}
			
		System.out.println("university: "+ ApplicationEx.getInstance().myProfile);
			universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
			if (universitydeals != null) {
				System.out.println("university deals is not null"+universitydeals.getSchoolName()+" "+ApplicationEx.getInstance().myProfile.isLogin());
				active = universitydeals.getMainDeal();
				if (active != null) {
					updateUniversityTheme();
					updateDealContents();
					tabtextWebViewHL.loadData(active.getHighLightsString(), "text/html", "utf-8");
					tabtextWebViewFP.loadData(active.getFinePrints(), "text/html", "utf-8");
					tabtextWebViewCOM.loadData(active.getCompanyString(), "text/html", "utf-8");
					
					
				} else {
					getTodaysDeal(universitydeals.getSchoolSlug());
				}
			}
		}
	

	public void initActiveDealsScreen() {
		header = (View) findViewById(R.id.header);

		headerButtonLeft = (Button) findViewById(R.id.header_iconleft);
		headerButtonRight = (Button) findViewById(R.id.header_iconright);
		headerButtonRight.setOnClickListener(this);

		headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
		headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);

		headerTitle = (TextView) findViewById(R.id.header_title);

		beanSays = (TextView) findViewById(R.id.button_beansay);

		mainpage = (RelativeLayout) findViewById(R.id.activedealsmain);
		maindeals = (RelativeLayout) findViewById(R.id.maindeals);
		maindeals.setBackgroundDrawable(ApplicationEx.getInstance().gradientGray_TOP_BOTTOM_ACTIVEDEALS);
		timer = (TextView) findViewById(R.id.timestamp);

		thumbnailLayout = (RelativeLayout) findViewById(R.id.dealsthumbnail_layout);
		thumbnailLayout.setBackgroundDrawable(ApplicationEx.getInstance().gradientGray_LEFT_RIGHT);

		/* tabs */
		tf_highLights = (Button) findViewById(R.id.button_highlight);
		tf_highLights.setSelected(true);

		tf_finePrint = (Button) findViewById(R.id.button_fineprint);
		tf_finePrint.setSelected(false);

		tf_company = (Button) findViewById(R.id.button_company);
		tf_company.setSelected(false);

		dealListView = (LinearLayout) findViewById(R.id.deallist);
		dealListView.setVisibility(View.GONE);

		setonclickListeners();
		
		// update universty specific themes
		updateUniversityTheme();
		
		// update data
		if (universitydeals != null && universitydeals.getMainDeal() != null) {
			active = universitydeals.getMainDeal();
			if(active!=null){
				tabtextWebViewHL.loadData(active.getHighLightsString(), "text/html", "utf-8");
				tabtextWebViewFP.loadData(active.getFinePrints(), "text/html", "utf-8");
				tabtextWebViewCOM.loadData(active.getCompanyString(), "text/html", "utf-8");
			}
			updateDealContents();
		}
	}

	public void reduceTimer() {
		synchronized (remainingTimer) {
			remainingTimer = remainingTimer - (1000);
			if (remainingTimer < 0){
				remainingTimer = (long) 0;
				dealExpiry();
				handler.removeCallbacks(runnable);
				handler.postDelayed(runnable, 1000);
			
			}
			
			
			
		}
	}

	public void dealExpiry(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
		builder.setMessage("This deal has just expired.")
		       .setCancelable(false)
		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel(); 
		        	   dialog.dismiss();
		        	   universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
		        	   if (ApplicationEx.getInstance().progressDialog != null){
							ApplicationEx.getInstance().progressDialog .setMessage("Fetching new deals. Please wait.");
						}
		        	   getTodaysDeal(universitydeals.getSchoolSlug());
						
	           }
		       });
		AlertDialog alert = builder.create();
		alert.show();

	}
	
	public void setonclickListeners() {
		headerButtonLeft.setOnClickListener(this);
		headerButtonRight.setOnClickListener(this);
		headerTitle.setOnClickListener(this);
		headerTitle.setClickable(true);
		headerTitle.setSelected(true);
		beanSays.setOnClickListener(this);
		findViewById(R.id.button_buy).setOnClickListener(this);
		findViewById(R.id.button_discuss).setOnClickListener(this);
		findViewById(R.id.button_share).setOnClickListener(this);

		tf_company.setOnClickListener(this);
		tf_highLights.setOnClickListener(this);
		tf_finePrint.setOnClickListener(this);

	}

	private void updateUniversityTheme() {
		if (universitydeals != null) {
			if (universitydeals.getSchoolTitle() != null) {
				headerTitle.setText(universitydeals.getSchoolTitle());
			}
			if (universitydeals.color_school_bg > -1) {
				// universitydeals.color_school_bg += (-16777216);

				if (header != null)
					header.setBackgroundColor(universitydeals.color_school_bg + (-16777216));

				if (mainpage != null)
					mainpage.setBackgroundColor(universitydeals.color_school_bg + (-16777216));
				ApplicationEx.getInstance().currentBG = universitydeals.color_school_bg + (-16777216);
			}

			if (universitydeals.getColor_titleBarBottomColor() > -1 && universitydeals.getColor_titleBarTopColor() > -1) {
				if (headerbottomBG != null) {
					headerbottomBG.setBackgroundColor(universitydeals.getColor_titleBarBottomColor() + (-16777216));
				}
				if (headertopBG != null)
					headertopBG.setBackgroundColor(universitydeals.getColor_titleBarTopColor() + (-16777216));
			}
			
			//update beanSays
			if (universitydeals.drawablImages!=null && universitydeals.drawablImages.drawable_beansay_btn_normal !=null){
				((RelativeLayout)findViewById(R.id.relative_beansay)).setBackgroundDrawable(universitydeals.drawablImages.drawable_beansay_btn_normal);
			}else 
				((RelativeLayout)findViewById(R.id.relative_beansay)).setBackgroundDrawable(null);

			updateTabUI();

		} // if university is not null
	}

	/* UPDATE IF YOUR JUST CHanging the deals */
	public void updateDealContents() {
		
		updateTabUI();
	
	if (active!=null){
		((TextView) findViewById(R.id.dealtitle)).setText(active.getDealName());
	
		((TextView) findViewById(R.id.dealprice)).setText(active.getDiscountPrice());
		((TextView) findViewById(R.id.timestamp)).setText(active.getTimeLeft());
		((TextView) findViewById(R.id.counter)).setText(active.getDealuserCount());

		((TextView) findViewById(R.id.originalprice)).setText(active.getOriginalPrice());
		((TextView) findViewById(R.id.discountpercent)).setText(active.getDiscountPercent());
		((TextView) findViewById(R.id.discountamount)).setText(active.getDiscountAmount());

		// get promot thumbnail
		if (active.thumbPromoImage == null) {
			getImage(active.getMediumImgUrl(), active.getDealID(), universitydeals.getSchoolSlug());
		} else {
				((ImageView) findViewById(R.id.dealsthumbnail)).setImageBitmap(active.thumbPromoImage);

		}
		
		// start timer
		startTimer(active);
	}
	}

	public void startTimer(ActiveDeal dealItem) {
		//System.out.println("########START  TIMER  ONCE########");
		handler.removeCallbacks(runnable);
		handler.postDelayed(runnable, 1000);
		
		remainingTimer = dealItem.getLeft();

	}
	
	
	public void updateRemainingTime() {
		synchronized (remainingTimer) {
			String date = Tools.setTimeBreakDown(remainingTimer);


			if (timer != null)
				timer.setText(date);

		}
	}

	public int getTabTextColor(boolean isSelected) {
		if (isSelected)
			return universitydeals.getColor_tabFontColorSelected();
		else
			return universitydeals.getColor_tabFontColorNormal();
	}

	public Drawable getTabDrawable(boolean isSelected) {
				if (isSelected){
			if (universitydeals.drawablImages!=null && universitydeals.drawablImages.drawable_tabSelected!=null)
				return universitydeals.drawablImages.drawable_tabSelected;
			else 
				return null;
		}else{
			if (universitydeals.drawablImages!=null && universitydeals.drawablImages.drawable_tabNormal!=null)
				return universitydeals.drawablImages.drawable_tabNormal;
			else{
				return null;
		
			}
		}
	}

	private void updateTabUI() {
	//	if its a no deals page ths does not need to be called()
		
		if (active!=null){
			tf_highLights.setBackgroundDrawable(getTabDrawable(tf_highLights.isSelected()));
			tf_highLights.setTextColor(getTabTextColor(tf_highLights.isSelected()));
			
			tf_finePrint.setBackgroundDrawable(getTabDrawable(tf_finePrint.isSelected()));
			tf_finePrint.setTextColor(getTabTextColor(tf_finePrint.isSelected()));
			
			tf_company.setBackgroundDrawable(getTabDrawable(tf_company.isSelected()));
			tf_company.setTextColor(getTabTextColor(tf_company.isSelected()));
			
			if (tf_highLights.isSelected()) {
				if (active != null &&active.getHighLightsString() != null) {
					tabtextWebViewHL.setVisibility(View.VISIBLE);
					tabtextWebViewHL.invalidate();
					tabtextWebViewFP.setVisibility(View.GONE);
					tabtextWebViewCOM.setVisibility(View.GONE);
				}
			} else if (tf_finePrint.isSelected()) {
				if (active != null && active.getFinePrints() != null) {
						tabtextWebViewFP.setFocusableInTouchMode(false); 
						tabtextWebViewFP.setVisibility(View.VISIBLE);
						tabtextWebViewFP.invalidate();
						tabtextWebViewHL.setVisibility(View.GONE);
						tabtextWebViewCOM.setVisibility(View.GONE);
				}
			} else if (tf_company.isSelected()) {
				if (active != null && active.getCompanyString() != null) {
					tabtextWebViewCOM.loadData(active.getCompanyString(), "text/html", "utf-8");
					tabtextWebViewCOM.setVisibility(View.VISIBLE);
					tabtextWebViewCOM.invalidate();
					tabtextWebViewHL.setVisibility(View.GONE);
					tabtextWebViewFP.setVisibility(View.GONE);
					//System.out.println("update company Done");

			}
		}
		if (universitydeals!=null && active !=null && active.getDescription()!=null)
			tabDescWebView.loadData(active.getDescription(), "text/html", "utf-8");

		((LinearLayout) findViewById(R.id.tab_description_container)).setBackgroundDrawable(null);
		((LinearLayout) findViewById(R.id.text_bg_container)).setBackgroundDrawable(null);

		((LinearLayout) findViewById(R.id.tab_description_container)).setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
		((LinearLayout) findViewById(R.id.text_bg_container)).setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
	}
	}
	@Override
	public void onClick(View v) {
		if (!ApplicationEx.getInstance().onDealsDropDown){
		if (v == tf_company || v == tf_finePrint || v == tf_highLights) {
			int id = v.getId();
			switch (id) {
			case R.id.button_fineprint:
				tf_finePrint.setSelected(true);
				tf_company.setSelected(false);
				tf_highLights.setSelected(false);
				break;
			case R.id.button_company:
				tf_finePrint.setSelected(false);
				tf_company.setSelected(true);
				tf_highLights.setSelected(false);
				break;
			case R.id.button_highlight:
				tf_finePrint.setSelected(false);
				tf_company.setSelected(false);
				tf_highLights.setSelected(true);
				break;
			default:
				break;
			}

			updateTabUI();

			return;

		}// end if
		else {
			int id = v.getId();
			
			switch (id) {
			case R.id.deallist:
				if (dealListView.getVisibility() == View.VISIBLE) {
					dealListView.setVisibility(View.INVISIBLE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_deals);
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.GONE);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.GONE);
				}
				break;
			case R.id.button_buy:
				
				if (dealListView.getVisibility() != View.VISIBLE) {
					callBuyActivity();
				}
				break;
			case R.id.button_share:
				showShareAlert();
				
				break;
			case R.id.button_beansay: {
				callBeansSaysActivity();
				break;
			}
			case R.id.button_discuss:
				callDiscussActivity();
				break;
			case R.id.header_iconleft: // schools
				handler.removeCallbacks(runnable);
				ApplicationEx.getInstance().currentTab = 0;
				ApplicationEx.getInstance().controller.current = this;
				Intent getSchoolIntent = new Intent(this, GetSchoolAllActivity.class);
				getSchoolIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(getSchoolIntent);
				break;
			case R.id.header_iconright: // deals
			{
				
				if (dealListView.getVisibility() == View.VISIBLE) {
					runClearList();
				}else{ 
					ApplicationEx.getInstance().onDealsDropDown = true;
					dealListView.setVisibility(View.VISIBLE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_done);
					headerButtonLeft.setVisibility(View.INVISIBLE);
					headerButtonRight.setTextColor(0xffffff);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.VISIBLE);
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.VISIBLE);
					showAllDealList();
				}
				break;
			}
			default: {
				if (v.getTag() != null) {
					int i = Integer.parseInt(v.getTag().toString());
					handler.removeCallbacks(runnable);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.GONE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_deals);
					headerButtonLeft.setVisibility(View.VISIBLE);
					ApplicationEx.getInstance().myProfile.getlastSelectedSchool().selectedDealIndex = i;
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.GONE);
					
					universitydeals.hasDeals = true;
					active = universitydeals.getMainDeal();
					
					//load tabs
					if(active!=null){
						tabtextWebViewHL.loadData(active.getHighLightsString(), "text/html", "utf-8");
						tabtextWebViewFP.loadData(active.getFinePrints(), "text/html", "utf-8");
						tabtextWebViewCOM.loadData(active.getCompanyString(), "text/html", "utf-8");
					}
					initActiveDealsScreen();
				}
				break;
			}

			}// end switch
		}// end if
		}else { //deal is drop down only thing clickable is the deals button
		 if (v.getId() == R.id.header_iconright)// deals
		{	
			// if (dealListView.getVisibility() == View.VISIBLE) {
					ApplicationEx.getInstance().onDealsDropDown = false;
					dealListView.setVisibility(View.GONE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_deals);
					headerButtonLeft.setVisibility(View.VISIBLE);
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.GONE);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.GONE);
				//}
			 		/*ApplicationEx.getInstance().onDealsDropDown = true;
					dealListView.setVisibility(View.VISIBLE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_done);
					headerButtonLeft.setVisibility(View.INVISIBLE);
					headerButtonRight.setTextColor(0xffffff);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.VISIBLE);
				
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.VISIBLE);
					showAllDealList();*/
					
		}else if (v.getTag() != null) {
				int i = Integer.parseInt(v.getTag().toString());
				handler.removeCallbacks(runnable);
				((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.GONE);
				headerButtonRight.setBackgroundResource(R.drawable.btn_deals);
				headerButtonLeft.setVisibility(View.VISIBLE);
				ApplicationEx.getInstance().myProfile.getlastSelectedSchool().selectedDealIndex = i;
				((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.GONE);
				
				universitydeals.hasDeals = true;
				active = universitydeals.getMainDeal();
				ApplicationEx.getInstance().onDealsDropDown = false;
				
				//load tabs
				if(active!=null){
					tabtextWebViewHL.loadData(active.getHighLightsString(), "text/html", "utf-8");
					tabtextWebViewFP.loadData(active.getFinePrints(), "text/html", "utf-8");
					tabtextWebViewCOM.loadData(active.getCompanyString(), "text/html", "utf-8");
				}
				initActiveDealsScreen();
		
			
		}
			
		}
	}
	

    // Create runnable for posting
    final Runnable mDealList = new Runnable() {
        public void run() {
        	clearDealList();
			
        }
    };
	 
    protected void runClearList() {
        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mHandler.post(mDealList);
            }
        };
        t.start();
    }
    
	 public void clearDealList() {
		  	if (ApplicationEx.getInstance().onDealsDropDown){
		  			ApplicationEx.getInstance().onDealsDropDown = false;
					dealListView.setVisibility(View.GONE);
					headerButtonRight.setBackgroundResource(R.drawable.btn_deals);
					headerButtonLeft.setVisibility(View.VISIBLE);
					((LinearLayout) findViewById(R.id.opaque)).setVisibility(View.GONE);
					((ScrollView) findViewById(R.id.deallistScroll)).setVisibility(View.GONE);
					
				}
	   		}
	
	 
	 
	private void showAllDealList() {
		dealList = universitydeals.getDeals();
		LinearLayout l = (LinearLayout) findViewById(R.id.deallist);
		l.removeAllViews();
		LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		for (int i = 0; i < dealList.size(); i++) {
			ActiveDeal activedeal = (ActiveDeal) dealList.get(i);
			customView = linflater.inflate(R.layout.contextmenu_item, null);
			TextView tv = (TextView) customView.findViewById(R.id.contextmenu_title);
			ImageView btn = (ImageView) customView.findViewById(R.id.contextenu_thumbnail);
			tv.setText(activedeal.getDealName());
			tv.setTypeface(null, Typeface.BOLD);

			btn.setImageBitmap(activedeal.thumbPromoImage);
			customView.setTag(i);
			customView.setId(i);
			customView.setOnClickListener(this);
			l.addView(customView);

		}
		
		l.setVisibility(View.VISIBLE);
		// l.startAnimation(contextMenuIn);

	}

	private void getTodaysDeal(String univId) {

		// start pulling the latest deals
		ArrayList<String> params = new ArrayList<String>();
		params.add(univId);
		new GetTodaysDealHandler(Tools.getURL(Constant.GET_TODAYS_DEAL, params),true);
	}

	private void callNoScreenDeals(String errorMessage) {

		Intent i = new Intent(this, NoDealsActivity.class);
		i.putExtra("deal_error_message", errorMessage);

		ApplicationEx.getInstance().myProfile.getlastSelectedSchool().hasDeals = false;
		
		View view = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager()
				.startActivity("NoActiveDeals", i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
		view.setId(Constant.ID_NOACTIVEDEALS);
        
		// Again, replace the view
		ActiveDealsActivityGroup.activedealsgroup.replaceView(view);
	}

	
	public void SignIn(String loginfrom){
		Intent intent = new Intent(this, LoginActivity.class);
		intent.putExtra(Constant.TAG_LOGINFROM, loginfrom);
		startActivity(intent);
 	}
	
	
	public void SignIn() {
		
		Intent intent = new Intent(this.getParent(), LoginActivity.class);
		intent.putExtra(Constant.TAG_LOGINFROM, Constant.TAG_LOGINFROM_BUYPAGE);
		startActivity(intent);
	}
	
	private void callBuyActivity() {
		
		//check if user has signed in
		
		if (!ApplicationEx.getInstance().myProfile.isLogin()) {
		
			SignIn();

		} else {
			Intent i = new Intent(getParent(), BuyActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			LocalActivityManager local = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager();
			
			
         	
			local.removeAllActivities();
			for (int a = 0; a<ApplicationEx.getInstance().history.size();a++){
	         	View vv = ApplicationEx.getInstance().history.get(a);
	        }
			
			View view = local.startActivity("BuyActivity", i).getDecorView();
			view.setId(Constant.ID_BUYACTIVEDEALS);
            
			// Again, replace the view
			//if (view!=null)
				ActiveDealsActivityGroup.activedealsgroup.replaceView(view);
			
			
		}
			
			
			
	}

	private void callBeansSaysActivity() {

		Intent i = new Intent(this.getParent(), BeansSaysActivity.class);

		View view = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager()
				.startActivity("BeansSay", i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
		view.setId(Constant.ID_BEANSAYS);
        
		// Again, replace the view
		ActiveDealsActivityGroup.activedealsgroup.replaceView(view);
	}
	private void gotoSignIn(){
		
		Intent intent = new Intent(this.getParent(), LoginActivity.class);
 	 	startActivity(intent);
		
	}
	private void callDiscussActivity(){
	         Intent i = new Intent(getParent(), DiscussActivity.class);
		     i.putExtra(Constant.TAG_COMPANY_DEALTITLE, active.getDealName());
			 i.putExtra(Constant.TAG_COMPANY_DEALID, active.getDealID());
			 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					
			 LocalActivityManager local = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager();
			 local.removeAllActivities();
					
			 View view = local.startActivity("Discuss", i).getDecorView();
			 view.setId(Constant.ID_DISCUSS);
			
			 // Again, replace the view
			ActiveDealsActivityGroup.activedealsgroup.replaceView(view);
	
	
			
			
			
	}

    protected void updateImageDeals() {
        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }
	 // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
        	updateDealContents();
			if (dealListView!=null && dealListView.isShown()){
				showAllDealList(); //update deallist
			}
        }
    };
    
    // Create runnable for posting
    final Runnable mImageGet = new Runnable() {
        public void run() {
        	Log.i("mImageGet","DOWNLOAD 2");

        	updateDrawable();
			
        }
    };
    
    public void downloadImage(final String slug){
		
		String PATH = "http://unimiser.com/img/slugimages/android/large/"+slug+".zip";
				try{
				ZipDownloader zip = new ZipDownloader();
				zip.listener =this;
				zip.execute(new String[]{PATH,slug});

			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	
}
    @Override
	public void updateScreen(boolean toUpdate) {
    	mHandler.post(mImageDisplay);
		
	}
  public DrawableImageSlug getDrawableImage(String slug){
	  
	  DrawableImageSlug result=null;
	  if (ApplicationEx.getInstance().drawableImages == null )
		  ApplicationEx.getInstance().drawableImages = new HashMap<String, DrawableImageSlug>();
	  
	  
	  if (ApplicationEx.getInstance().drawableImages.size() == 0)//download images
	  {
		  Log.e("DrawableImageSlug","size is zero downoad the images");
		  	
		  downloadImage(slug);
		 
	  }
	  
	  if (!ApplicationEx.getInstance().drawableImages.containsKey(slug)) //download images
	  {
		  Log.e("DrawableImageSlug",ApplicationEx.getInstance().drawableImages+" "+slug);
			 
		  downloadImage(slug);
		
	  }  
	   result = (ApplicationEx.getInstance().drawableImages).get(slug);
	  return result;
  }
    private void updateDrawable(){
    	if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages == null)
    		ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages = new DrawableImageSlug(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getImageSlug());
    	
    	//check db if slug exist
    	
    	//else download it
    	ApplicationEx.getInstance().myProfile.getlastSelectedSchool().drawablImages = getDrawableImage(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getImageSlug());
    	
    		
    		
    	
    }
 // Create runnable for posting
    final Runnable mImageDisplay = new Runnable() {
        public void run() {
        	updateLatestScreen();
        	
        }
    };
    
    public void updateLatestScreen(){
    
    	universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
    	universitydeals.drawablImages = ApplicationEx.getInstance().drawableImages.get(universitydeals.getImageSlug());
    	if (universitydeals!=null && universitydeals.getDeals()!=null && universitydeals.getDeals().size()>0){
         	// update UI
			fetchImages(universitydeals);
			active = universitydeals.getMainDeal();
			
			updateUniversityTheme();
			
			updateDealContents();
	    	
    	}else if (universitydeals!=null){
        	universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
			callNoScreenDeals(errormessage);
			
		}
    	
			
    }
	public BroadcastReceiver activeDealsBRoadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("onreceive","ACTIVEDEALS"+intent.getAction());
			if (intent.getAction().equals(Constant.EVENTS_GETACTIVEDEALS_ERROR)) {
				uiIntent = intent;
				ApplicationEx.getInstance().onReceieveError = true;
				errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
				
				universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
				Log.i("mImageGet","no deals 1");
				mHandler.post(mImageGet);
				callNoScreenDeals(errormessage);
				
			} else if (intent.getAction().equals(Constant.EVENTS_GETACTIVEDEALS_SUCCESS)) {
				// update UI
				
				uiIntent = intent;
				universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
				Log.i("mImageGet","step 1");

				mHandler.post(mImageGet);
				fetchImages(universitydeals);
				active = universitydeals.getMainDeal();
				updateUniversityTheme();
				updateDealContents();
				
				
			}else if (intent.getAction().equals(Constant.EVENTS_GETBITMAPIMAGE)) {
				uiIntent = intent;
				if (universitydeals == null)
						universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
						active = universitydeals.getMainDeal();
						updateImageDeals();
		
			} else if (intent.getAction().equals("SCHOOLLISTSELECTED")) {
				uiIntent = intent;
				universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
				getTodaysDeal(universitydeals.getSchoolSlug());

			}

		}
	};

	public void fetchImages(UniversityDeals universityDeals) {
		ArrayList<ActiveDeal> items = universityDeals.getDeals();
		
		for (int i = 0; i < items.size(); i++) {
			ActiveDeal item = items.get(i);
			getImage(item.getMediumImgUrl(), item.getDealID(), universityDeals.getSchoolSlug());
		}
		

	}

	public void getImage(final String feed, final String dealId, final String universitySlug) {
		final ImageListener listener = this;
		// In all cases, start a background thread.
		Thread thread = new Thread() {
			public void run() {
				try {
					Thread.sleep(1);
					ImageEngine.getInstance().getImage(new ObjectImage(feed, listener, dealId, universitySlug));
				} catch (InterruptedException ex) {
				}
			}

		};
		thread.start();
	}

	@Override
	public void imageResponse(Bitmap bitmap, String imgId, String universityId) {

		// TODO Auto-generated method stub
		//System.out.println("IMAGE RESPONSE "+imgId+" "+universityId+" "+universitydeals.getSchoolSlug());
		if (bitmap != null && imgId != null && universityId != null) {
				if (universityId == (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolSlug())){
					if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().dealHashMap.containsKey(imgId)) {
						ActiveDeal updatedDeal = ApplicationEx.getInstance().myProfile.getlastSelectedSchool().dealHashMap.get(imgId);
						updatedDeal.thumbPromoImage = bitmap;
						updatedDeal.promoMapImage = Tools.getResizedBitmap(bitmap, 100,150);
						ApplicationEx.getInstance().myProfile.getlastSelectedSchool().updateHashMap(updatedDeal, imgId);
					}
				}else if (universityId == (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolSlug())){
					if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().dealHashMap.containsKey(imgId)) {
						ActiveDeal updatedDeal = ApplicationEx.getInstance().myProfile.getlastSelectedSchool().dealHashMap.get(imgId);
						updatedDeal.thumbPromoImage = bitmap;
						updatedDeal.promoMapImage = Tools.getResizedBitmap(bitmap, 100,150);
						ApplicationEx.getInstance().myProfile.getlastSelectedSchool().updateHashMap(updatedDeal, imgId);
					}
				}
			Intent intent = new Intent(Constant.EVENTS_GETBITMAPIMAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
		}

	}

	private void showShareAlert() {

		ShareItem[] items = new ShareItem[3];

		for (int i = 0; i < shareitems.length; i++) {
			items[i] = new ShareItem(shareitems[i], getImg(shareitemsdrawable[i]));
		}

		ListAdapter adapter = new ShareAdapter(this.getParent(), items);
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
		builder.setTitle("Share this deal");
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});

		builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				System.out.println("click items in share");
				// a choice has been made!
				//String selectedVal = items[which].getName();
				switch (which) {
				case 0:
					sendEmail();
					break;
				case 1:
					shareViaFacebook();// post to facebook
					break;
				case 2:
				   shareViaTwitter();
					break;
				default:
					break;
				}
				dialog.dismiss();
			}
		});

		builder.show();

	}
private void shareViaTwitter(){
	 
	String dealstitle = active.getDealName()+"@"+active.getCompany().getCompanyname();
	
	 Intent i = new Intent(getParent(), TwitterActivity.class);  
	 i.putExtra(Constant.TAG_TWITTER_MESSAGE, dealstitle);
	
	 LocalActivityManager local  =  ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager() ;
	 
	 local.removeAllActivities();
	 
	 View view = local.startActivity("TwitterShare",  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();  
	   
	         // Again, replace the view
	         ActiveDealsActivityGroup.activedealsgroup.replaceView(view);


}
private void shareViaFacebook(){
	String dealstitle = active.getDealName();
	String companyName = active.getCompany().getCompanyname();
	String facebookurl = active.getFacebookshare_url();
	String thumbnailurl = active.getMediumImgUrl();
	
	System.out.println("SHARE VIA FACEBOOK");
	 
	 Intent i = new Intent(this.getParent(), FaceBookShareActivity.class);  
	
	 System.out.println(dealstitle+" "+companyName+"URL: "+facebookurl+" "+thumbnailurl);
	 i.putExtra(Constant.TAG_COMPANY_DEALTITLE, dealstitle);
	 i.putExtra(Constant.TAG_COMPANY_NAME, companyName);
	 i.putExtra(Constant.TAG_FACEBOOK_URL, facebookurl);
	 i.putExtra(Constant.TAG_DEAL_THUMBNAIL, thumbnailurl);
		 
	 
		
	 LocalActivityManager local = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager();
	 local.removeAllActivities();
			
	 View view = local.startActivity("FacebookShare", i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); 
	
	 
	 // Again, replace the view
	 ActiveDealsActivityGroup.activedealsgroup.replaceView(view);


}

	private Drawable getImg(int res) {
		Drawable img = getResources().getDrawable(res);
		// img.setBounds( 0, 0, 48, 48 );
		return img;
	}

	public void sendEmail() {
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { " " });
		
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"I think you should get your BigFreakinDeals: "+active.getDealName());
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,active.getDealName()+"\n\n"+active.getQuick_email_friend_url());
		
		startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(activeDealsBRoadcastReceiver);

	} 
	   public void setConfirmAlert(final int keyCode, final KeyEvent event){
		   
		  	AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
				builder.setMessage("Do you want to exit BigFreakinDeals app?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   dialog.cancel(); 
				        	   dialog.dismiss();
				        	   	ApplicationEx.getInstance().isConfirm = true;
				        	   if (event == null)
				        		onBackPressed();
				        	   else
				        		   onKeyDown(keyCode, event);
				        	   
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				                ApplicationEx.getInstance().isConfirm = false;
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				
			}

	   @Override    
	   public void onBackPressed() {
		   System.out.println("onback pressed of group"+ApplicationEx.getInstance().history.size());
		  if (ApplicationEx.getInstance().onDealsDropDown){
		   	System.out.println("super on back pressed");
		   	  onClick(headerButtonRight);
		   		}
	   }




}
